/*
 * HttpData.h
 *
 *  Created on: 2021年4月6日
 *      Author: san
 */

#ifndef HTTPDATA_H_
#define HTTPDATA_H_

#include <sys/epoll.h>
#include <unistd.h>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include "Timer.h"
#include "states.h"

namespace san {

class EventLoop;
class TimerNode;
class Channel;


/*
 * 静态工具类
 */
class MimeType {
private:
	static void init();
	static std::unordered_map<std::string, std::string> mime;
	MimeType();
	MimeType(const MimeType &m);

public:
	static std::string getMime(const std::string &suffix);

private:
	// 单例控制
	static pthread_once_t once_control;
};

class HttpData : public std::enable_shared_from_this<HttpData> {
public:
	HttpData(EventLoop *loop, int connfd);
	~HttpData() {close(fd_);}
	void reset();
	void seperateTimer();

	void linkTimer(std::shared_ptr<TimerNode> mtimer)
	{
		timer_ = mtimer;
	}

	std::shared_ptr<Channel> getChannel() { return channel_; }
	EventLoop *getLoop() { return loop_; }
	void handleClose();
	void newEvent();

private:

	void handleRead();
	void handleWrite();
	void handleConn();
	void handleError(int fd, int err_num, std::string short_msg);
	URIState parseURI();                // 解析URI
	HeaderState parseHeaders();         // 解析请求头
	AnalysisState analysisRequest();    // 处理业务请求

	EventLoop *loop_;
	std::shared_ptr<Channel> channel_;  // 当前channel
	int fd_;
	std::string inBuffer_;
	std::string outBuffer_;
	bool error_;

	// 记录连接状态
	ConnectionState connectionState_;

	HttpMethod method_;
	HttpVersion http_version_;
	std::string fileName_;
	std::string path_;
	int nowReadPos_;
	ProcessState state_;
	ParseState hState_;
	bool keepAlive_;
	std::map<std::string, std::string> headers_;
	std::weak_ptr<TimerNode> timer_;
};

} /* namespace san */

#endif /* HTTPDATA_H_ */
